package imageviewer.beans;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.net.URL;
import java.sql.Connection;
import java.sql.Date;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import imageviewer.persistence.Database;


import imageviewer.domain.Camera;
import imageviewer.domain.Picture;


public class OverViewBean extends BasicBean {

	Vector<Picture> pictures = null;
	
	Date dayFrom = null;;
	Date dayTo = null;;
	Date day = null;;
	Long userID = null;;
	String[] cameraIDs = null;
	String timeFrom = null;
	String timeTo = null;
	
	

	public Date getDay() {
		return day;
	}

	public void setDay(Date day) {
		this.day = day;
	}

	public Date getDayFrom() {
		return dayFrom;
	}

	public void setDayFrom(Date dayFrom) {
		this.dayFrom = dayFrom;
	}

	public Date getDayTo() {
		return dayTo;
	}

	public void setDayTo(Date dayTo) {
		this.dayTo = dayTo;
	}

	public Vector<Picture> getPictures() {
		return pictures;
	}

	public void setPictures(Vector<Picture> pictures) {
		this.pictures = pictures;
	}

	public String getTimeFrom() {
		return timeFrom;
	}

	public void setTimeFrom(String timeFrom) {
		this.timeFrom = timeFrom;
	}

	public String getTimeTo() {
		return timeTo;
	}

	public void setTimeTo(String timeTo) {
		this.timeTo = timeTo;
	}

	public Long getUserID() {
		return userID;
	}

	public void setUserID(Long userID) {
		this.userID = userID;
	}
	
	public void getThumbnail(String Path, OutputStream out) throws IOException{
		FileInputStream is = new FileInputStream(Path);
		int readBytes = 0;
		do {
			readBytes = is.read();
			out.write(readBytes);
		} while (readBytes >= 0);
		out.flush();
		out.close();
		is.close();
	}

	public void fetchOverView() {
		pictures = new Vector<Picture>();
		String camera = cameraIdToString(cameraIDs);
		if(camera.equals("")){
			super.setUserMessage("Bitte waehlen Sie eine Kamera!");
			super.setError(true);
			return;
		}
		if(dayFrom != null && dayFrom.getTime() > dayTo.getTime()){
			super.setUserMessage("Ueberpruefen sie das Datum!");
			super.setError(true);
			return;
		}
		String time;
		if(day != null)
			time = "AND mydate = TO_DATE('"+day+"','YYYY-MM-DD')  ";
		else {
			Pattern p = Pattern.compile("[0-9]{2}:[0-9]{2}");

			Matcher m1 = p.matcher(timeFrom);
			Matcher m2 = p.matcher(timeTo);
			if(!(m1.matches() && m2.matches())){
				super.setUserMessage("Fehlerhafte Uhrzeit! Stunden, Minuten muessen zweistellig angegeben werden z.B. 04:22");
				super.setError(true);
				return;
			} else {
				int from = Integer.valueOf(timeFrom.substring(0, 2)).intValue();
				int to = Integer.valueOf(timeTo.substring(0, 2)).intValue();
				if(!(from < 24 && to < 24))
					super.setError(true);
				from = Integer.valueOf(timeFrom.substring(3, 5)).intValue();
				to = Integer.valueOf(timeTo.substring(3, 5)).intValue();
				if(!(from < 60 && to < 60))
					super.setError(true);
				if(super.isError()){
					super.setUserMessage("Fehlerhafte Uhrzeit! Angegebene Uhrzeit existiert nicht");
					return;
				}
			}

			time = "AND time between '" + dayFrom.toString() + " " + timeFrom + "' and '" + dayTo.toString() + " " + timeTo + "'"; 
		}
		
		
		Connection con = Database.getConnection();
		String query = "SELECT p.name, p.pic_id, p.Mydate, p.time, p.thumbnail, c.url, c.camera_id, c.name, p.PIC_DATA_ID "+
			"FROM Camera c, User_Camera uc, Users u, Picture p "+
			"WHERE u.user_id = uc.user_id "+
			"AND uc.camera_id = c.camera_id AND c.camera_id = p.camera_id "+
			time+
			"AND u.user_id = "+userID+" AND c.camera_id IN ("+camera+")"+
			"order by p.time";
		fillPictures(con, query);		

	}

	private String cameraIdToString(String[] cameraIDs) {
		String camera = "";
		if (cameraIDs != null) {
			for (int i = 0; i < cameraIDs.length; i++)
				camera += "," + cameraIDs[i];
			camera = camera.replaceFirst(",", "");
		}
		return camera;
	}


	private void fillPictures(Connection con, String query) {
		try {
			Statement smt = con.createStatement();
			ResultSet rs = smt.executeQuery(query);
			while(rs.next()){					
				 Picture pic = new Picture();
				 pic.setName(rs.getString(1));
				 pic.setId(rs.getLong(2));
				 pic.setDate(rs.getDate(3));
				 pic.setTime(rs.getString(4));
				 pic.setPath(rs.getString(5));
				 pic.setPicDataId(rs.getLong(9));


//				 camera
				 pic.setCamera(new Camera(new URL(rs.getString(6)), rs.getString(8), rs.getLong(7)));

				 pictures.add(pic); 
			}
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String[] getCameraIDs() {
		return cameraIDs;
	}

	public void setCameraIDs(String[] cameraIDs) {
		this.cameraIDs = cameraIDs;
	}





}
